<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/Frog_32px_1177822_easyicon.net.ico">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/Frog_32px_1177822_easyicon.net.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/Frog_16px_1177822_easyicon.net.ico">
  <link rel="mask-icon" href="/images/Frog_32px_1177822_easyicon.net.ico" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="/lib/pace/pace-theme-minimal.min.css">
  <script src="/lib/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"hxy1997.xyz","root":"/","scheme":"Pisces","version":"7.8.0","exturl":false,"sidebar":{"position":"left","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":"valine","storage":true,"lazyload":true,"nav":null,"activeClass":"valine"},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"输入关键字","hits_empty":"没有找到与「${query}」相关搜索","hits_stats":"${hits} 条相关记录，共耗时 ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.json"};
  </script>

  <meta name="description" content="继续抱佛脚，从0开始编写一个自己的 webpack 插件。">
<meta property="og:type" content="article">
<meta property="og:title" content="从0开始编写webpack插件">
<meta property="og:url" content="https://hxy1997.xyz/2021/06/02/%E4%BB%8E0%E5%BC%80%E5%A7%8B%E7%BC%96%E5%86%99webpack%E6%8F%92%E4%BB%B6/index.html">
<meta property="og:site_name" content="hxy的博客">
<meta property="og:description" content="继续抱佛脚，从0开始编写一个自己的 webpack 插件。">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-06-02T13:07:33.000Z">
<meta property="article:modified_time" content="2021-06-14T09:34:01.177Z">
<meta property="article:author" content="hxy">
<meta property="article:tag" content="实战">
<meta property="article:tag" content="webpack">
<meta property="article:tag" content="插件">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://hxy1997.xyz/2021/06/02/%E4%BB%8E0%E5%BC%80%E5%A7%8B%E7%BC%96%E5%86%99webpack%E6%8F%92%E4%BB%B6/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>从0开始编写webpack插件 | hxy的博客</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="hxy的博客" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">hxy的博客</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">Mia san Mia!</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>

  <a href="https://github.com/huxingyi1997" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://hxy1997.xyz/2021/06/02/%E4%BB%8E0%E5%BC%80%E5%A7%8B%E7%BC%96%E5%86%99webpack%E6%8F%92%E4%BB%B6/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/Robben.gif">
      <meta itemprop="name" content="hxy">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="hxy的博客">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          从0开始编写webpack插件
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2021-06-02 21:07:33" itemprop="dateCreated datePublished" datetime="2021-06-02T21:07:33+08:00">2021-06-02</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-06-14 17:34:01" itemprop="dateModified" datetime="2021-06-14T17:34:01+08:00">2021-06-14</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/web%E5%89%8D%E7%AB%AF/" itemprop="url" rel="index"><span itemprop="name">web前端</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="热度" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">热度：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="far fa-comment"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/2021/06/02/%E4%BB%8E0%E5%BC%80%E5%A7%8B%E7%BC%96%E5%86%99webpack%E6%8F%92%E4%BB%B6/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/2021/06/02/%E4%BB%8E0%E5%BC%80%E5%A7%8B%E7%BC%96%E5%86%99webpack%E6%8F%92%E4%BB%B6/" itemprop="commentCount"></span>
    </a>
  </span>
  
  

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>继续抱佛脚，从0开始编写一个自己的 <code>webpack</code> 插件。</p>
<span id="more"></span>

<h2 id="1-前言"><a href="#1-前言" class="headerlink" title="1. 前言"></a>1. 前言</h2><p>插件(plugins)是 <code>webpack</code> 中的一等功臣。正是由于有了诸多插件的存在，才使得 <code>webpack</code> 无所不能。在 <code>webpack</code> 源码中也是使用了大量的内部插件，插件要是用的好，可以让你的工作效率事半功倍。用了别人写的插件很爽，那么我们何不考虑编写一个自己的插件呢？本篇文章就来教你如何编写一个自己的 <code>webpack</code> 插件。</p>
<h2 id="2-webpack运行机制"><a href="#2-webpack运行机制" class="headerlink" title="2. webpack运行机制"></a>2. webpack运行机制</h2><p>在编写插件之前，我们有必要先了解一下 <code>webpack</code> 的整体运行机制。 <code>Webpack</code> 的运行机制本质上是一种事件流的机制，在 <code>webpack</code> 运行过程中，从初始化参数、开始编译文件、确定入口、编译模块、编译完成、生成资源、输出资源、全部完成等等一系列过程，在这整个过程中的每一个节点， <code>webpack</code> 都会向外广播一个事件，我们可以通过监听每一个事件，在合适的时机通过 <code>webpack</code> 提供的 <code>API</code> 做一些合适的事情。</p>
<p><strong>通俗易懂的解释：</strong></p>
<p>如果上面的文字你不理解的话，那么我们以一个通俗易懂的例子再加以解释，如下：</p>
<p>我们把 <code>webpack</code> 比作一个厨师，而把 <code>webpack</code> 的整个运行过程比作厨师要炒一道菜，菜名就叫酸辣土豆丝。那么从准备要做这道菜到这道菜做好盛盘大概一共要经历以下几道工序：洗菜——切菜——炒菜——盛盘。并且我们跟厨师约定好，当厨师每进行一道工序的时候就让他大喊出这道工序的名称，即让厨师广播出一个事件，例如当厨师开始洗菜的时候，就让厨师大喊：“洗菜”。如果没有其他要求，那么这道酸辣土豆丝在经过如上四道工序后就可以完成啦。但是，我们有一个额外要求，就是想让这道酸辣土豆丝更辣一些。而原本的厨师只会按照正常的工序做，并不会额外的加辣椒，那要怎么办呢？此时我们的插件就登场啦，我们就需要编写一个“加辣椒”的插件。编写之前我们先要考虑这个辣椒在什么时候加合适，也就是说我们该监听哪一道工序，很明显，在炒菜的时候加。那么我们就监听“炒菜”这道工序，一旦厨师广播了这个事件，即大喊“炒菜”的时候，我们就把辣椒加进去，这样最后做出来的酸辣土豆丝就会更辣一些。</p>
<p><strong>总结来说：</strong></p>
<p><code>Webpack</code> 就像一条生产线，要经过一系列处理流程后才能将源文件转换成输出结果。 这条生产线上的每个处理流程的职责都是单一的，多个流程之间有存在依赖关系，只有完成当前处理后才能交给下一个流程去处理。 插件就像是一个插入到生产线中的一个功能，在特定的时机对生产线上的资源做处理。</p>
<p><code>Webpack</code> 通过 <a target="_blank" rel="noopener" href="https://github.com/webpack/tapable">Tapable</a>来组织这条复杂的生产线。 <code>Webpack</code> 在运行过程中会广播事件，插件只需要监听它所关心的事件，就能加入到这条生产线中，去改变生产线的运作。 <code>Webpack</code> 的事件流机制保证了插件的有序性，使得整个系统扩展性很好。</p>
<p>OK，相信现在你已经该对 <code>webpack</code> 的运行机制有个初步的理解了。接下来，我们就开始逐步编写插件。</p>
<h2 id="3-编写插件"><a href="#3-编写插件" class="headerlink" title="3. 编写插件"></a>3. 编写插件</h2><p>我们知道，在我们通常使用别人的插件时往往是像如下方式使用的：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">  entry: <span class="string">&#x27;&#x27;</span>,</span><br><span class="line">  output: &#123;&#125;,</span><br><span class="line">  <span class="built_in">module</span>: &#123;&#125;,</span><br><span class="line">  plugins: [</span><br><span class="line">    <span class="keyword">new</span> XXXPlugin(options)</span><br><span class="line">  ]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>从上面代码中我们可以看到，使用插件时往往都是 <code>new XXXPlugin()</code> ，那么换句话说一个插件就是一个类，使用该插件就是 <code>new</code> 一个该插件的实例，并且把插件所需要的配置参数传给该类的构造函数。那么我们就可以写出编写插件的第一步，如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">XXXPlugin</span> </span>&#123;</span><br><span class="line">  <span class="comment">// 在构造函数中获取用户给该插件传入的配置</span></span><br><span class="line">  <span class="function"><span class="title">constructor</span>(<span class="params">options</span>)</span> &#123;</span><br><span class="line">    <span class="built_in">this</span>.options = options;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 导出 Plugin</span></span><br><span class="line"><span class="built_in">module</span>.exports = XXXPlugin;</span><br></pre></td></tr></table></figure>

<p>接着，通过阅读 <code>webpack</code> 源码<a target="_blank" rel="noopener" href="https://github.com/webpack/webpack/blob/master/lib/webpack.js##L46">webpack.js:46行</a>我们知道：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> (options.plugins &amp;&amp; <span class="built_in">Array</span>.isArray(options.plugins)) &#123;</span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">const</span> plugin <span class="keyword">of</span> options.plugins) &#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">typeof</span> plugin === <span class="string">&quot;function&quot;</span>) &#123;</span><br><span class="line">      plugin.call(compiler, compiler);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      plugin.apply(compiler);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>当 <code>webpack</code> 内部在调用插件时会调用插件实例的 <code>apply</code> 方法，并为其传入 <code>compiler</code> 对象，OK，那么编写插件的第二步就来了，给插件类添加 <code>apply</code> 方法：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">XXXPlugin</span> </span>&#123;</span><br><span class="line">  <span class="comment">// 在构造函数中获取用户给该插件传入的配置</span></span><br><span class="line">  <span class="function"><span class="title">constructor</span>(<span class="params">options</span>)</span> &#123;</span><br><span class="line">    <span class="built_in">this</span>.options = options;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// Webpack 会调用 XXXPlugin 实例的 apply 方法给插件实例传入 compiler 对象</span></span><br><span class="line">  <span class="function"><span class="title">apply</span>(<span class="params">compiler</span>)</span> &#123;</span><br><span class="line">      </span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 导出 Plugin</span></span><br><span class="line"><span class="built_in">module</span>.exports = XXXPlugin;</span><br></pre></td></tr></table></figure>

<p>那么，这个 <code>complier</code> 又是什么？在这里我们有必要详细说明一下：</p>
<p>在开发 <code>Plugin</code> 时最常用的两个对象就是 <code>Compiler</code> 和 <code>Compilation</code> ，它们都继承自 <code>Tapable</code> ，是 <code>Plugin</code> 和 <code>Webpack</code> 之间的桥梁。 <code>Compiler</code> 和 <code>Compilation</code> 的含义如下：</p>
<ul>
<li><code>Compiler</code> 对象代表了完整的 <code>webpack</code> 环境配置。这个对象在启动 <code>webpack</code> 时被一次性建立，并配置好所有可操作的设置，包括 <code>options</code>，<code>loader</code> 和 <code>plugin</code>。当在 <code>webpack</code> 环境中应用一个插件时，插件将收到此 <code>Compiler</code> 对象的引用。可以使用它来访问 <code>webpack</code> 的主环境。</li>
<li><code>Compilation</code>对象代表了一次资源版本构建。当运行<code>webpack</code> 开发环境中间件时，每当检测到一个文件变化，就会创建一个新的 <code>Compilation</code>，从而生成一组新的编译资源。一个 <code>Compilation</code>对象表现了当前的模块资源、编译生成资源、变化的文件、以及被跟踪依赖的状态信息。<code>Compilation</code>对象也提供了很多关键时机的回调，以供插件做自定义处理时选择使用。</li>
</ul>
<p><code>Compiler</code> 和 <code>Compilation</code> 的区别在于： <code>Compiler</code> 代表了整个 <code>Webpack</code> 从启动到关闭的生命周期，而 <code>Compilation</code> 只是代表了一次新的编译。</p>
<p>使用 <code>Compiler</code> 对象就可以访问 <code>webpack</code> 的主环境，就可以监听到 <code>webpack</code> 在运行过程中所广播出的一系列事件。OK，到这里我们才搞明白，<strong>一个插件的核心部分原来是在 <code>apply</code> 方法里，在该方法里通过监听 <code>webpack</code> 在合适时机的广播出的事件然后做一些合适的事情。</strong>此时，你可能还有个疑问：<strong>我们该监听哪个事件？或者说webpack在整个流程中都广播了哪些事件？</strong>接下来，我们就通过阅读源码来 <code>webpack</code> 看看在整个运行过程中都广播出了哪些事件。</p>
<h2 id="4-webpack工作流程"><a href="#4-webpack工作流程" class="headerlink" title="4. webpack工作流程"></a>4. webpack工作流程</h2><p><code>Webpack</code> 的工作流程是一个串行的过程，从启动到结束会依次执行以下流程：</p>
<ul>
<li><strong>初始化参数：</strong>从配置文件和 <code>Shell</code> 语句中读取与合并参数，得出最终的参数；</li>
<li><strong>开始编译：</strong>用上一步得到的参数初始化 <code>Compiler</code> 对象，加载所有配置的插件，执行对象的<code>run</code>方法开始执行编译；</li>
<li><strong>确定入口：</strong>根据配置中的 <code>entry</code> 找出所有的入口文件</li>
<li><strong>编译模块：</strong>从入口文件出发，调用所有配置的 Loader 对模块进行编译，再找出该模块依赖的模块，再递归本步骤直到所有入口依赖的文件都经过了本步骤的处理；</li>
<li><strong>完成模块编译：</strong>在经过第4步使用 <code>Loader</code> 翻译完所有模块后，得到了每个模块被翻译后的最终内容以及它们之间的依赖关系；</li>
<li><strong>输出资源：</strong>根据入口和模块之间的依赖关系，组装成一个个包含多个模块的 <code>Chunk</code>，再把每个 <code>Chunk</code> 转换成一个单独的文件加入到输出列表，这步是可以修改输出内容的最后机会；</li>
<li><strong>输出完成：</strong>在确定好输出内容后，根据配置确定输出的路径和文件名，把文件内容写入到文件系统。</li>
</ul>
<p>在以上过程中， <code>Webpack</code> 会在特定的时间点广播出特定的事件，插件在监听到感兴趣的事件后会执行特定的逻辑，并且插件可以调用 <code>Webpack</code> 提供的 <code>API</code> 改变 <code>Webpack</code> 的运行结果。</p>
<p>按照广播的事件又可大致分为三大阶段：初始化阶段、编译阶段、输出阶段。三个阶段所发生的部分常用事件如下。</p>
<h3 id="4-1-初始化阶段"><a href="#4-1-初始化阶段" class="headerlink" title="4.1 初始化阶段"></a>4.1 初始化阶段</h3><table>
<thead>
<tr>
<th align="left">事件名</th>
<th align="left">解释</th>
</tr>
</thead>
<tbody><tr>
<td align="left">初始化参数</td>
<td align="left">从配置文件和Shell 语句中读取与合并参数，得出最终的参数。</td>
</tr>
<tr>
<td align="left">实例化 Compiler</td>
<td align="left">1. 用上一步得到的参数初始化 Compiler 实例 2. Compiler 负责文件监听和启动编译 3. Compiler 实例中包含了完整的 Webpack 配置，全局只有一个 Compiler 实例。</td>
</tr>
<tr>
<td align="left">加载插件</td>
<td align="left">1. 依次调用插件的 apply 方法，让插件可以监听后续的所有事件节点。 同时给插件传入 compiler 实例的引用，以方便插件通过 compiler 调用 Webpack 提供的 API。</td>
</tr>
<tr>
<td align="left">environment</td>
<td align="left">开始应用Node.js 风格的文件系统到compiler 对象，以方便后续的文件寻找和读取</td>
</tr>
<tr>
<td align="left">entry-option</td>
<td align="left">读取配置的 Entrys，为每个 Entry 实例化一个对应的 EntryPlugin，为后面该 Entry 的递归解析工作做准备</td>
</tr>
<tr>
<td align="left">after-plugins</td>
<td align="left">调用完所有内置的和配置的插件的apply 方法</td>
</tr>
<tr>
<td align="left">after-resolvers</td>
<td align="left">根据配置初始化resolver, resolver 负责在文件系统中寻找指定路径的文件</td>
</tr>
</tbody></table>
<h3 id="4-2-编译阶段"><a href="#4-2-编译阶段" class="headerlink" title="4.2 编译阶段"></a>4.2 编译阶段</h3><table>
<thead>
<tr>
<th align="left">事件名</th>
<th align="left">解释</th>
</tr>
</thead>
<tbody><tr>
<td align="left">run</td>
<td align="left">启动一次新的编译</td>
</tr>
<tr>
<td align="left">watch-run</td>
<td align="left">和run 类似，区别在于它是在监听模式下启动编译，在这个事件中可以获取是哪些文件发生了变化从而导致重新启动一次新的编译</td>
</tr>
<tr>
<td align="left">compile</td>
<td align="left">该事件是为了告诉插件一次新的编译将要启动，同时会给插件传入compiler 对象。</td>
</tr>
<tr>
<td align="left">compilation</td>
<td align="left">当 Webpack 以开发模式运行时，每当检测到文件变化，一次新的 Compilation 将被创建。 一个 Compilation 对象包含了当前的模块资源、编译生成资源、变化的文件等。 Compilation 对象也提供了很多事件回调供插件做扩展。</td>
</tr>
<tr>
<td align="left">make</td>
<td align="left">一个新的 Compilation 创建完毕主开始编译</td>
</tr>
<tr>
<td align="left">after-compile</td>
<td align="left">一次Compilation 执行完成</td>
</tr>
<tr>
<td align="left">invalid</td>
<td align="left">当遇到文件不存在、文件编译错误等异常时会触发该事件，该事件不会导致Webpack 退出</td>
</tr>
</tbody></table>
<h3 id="4-3-输出阶段"><a href="#4-3-输出阶段" class="headerlink" title="4.3 输出阶段"></a>4.3 输出阶段</h3><table>
<thead>
<tr>
<th align="left">事件名</th>
<th align="left">解释</th>
</tr>
</thead>
<tbody><tr>
<td align="left">seal</td>
<td align="left">所有模块及其依赖的模块都通过Loader 转换完成，根据依赖关系开始生成Chunk</td>
</tr>
<tr>
<td align="left">addChunk</td>
<td align="left">生成资源</td>
</tr>
<tr>
<td align="left">createChunkAssets</td>
<td align="left">创建资源</td>
</tr>
<tr>
<td align="left">getRenderManifest</td>
<td align="left">获得要渲染的描述文件</td>
</tr>
<tr>
<td align="left">render</td>
<td align="left">渲染源码</td>
</tr>
<tr>
<td align="left">afterCompile</td>
<td align="left">编译结束</td>
</tr>
<tr>
<td align="left">shouldEmit</td>
<td align="left">所有需要输出的文件已经生成好，询问插件哪些文件需要输出，哪些不需要。</td>
</tr>
<tr>
<td align="left">emit</td>
<td align="left">确定好要输出哪些文件后，执行文件输出，可以在这里获取和修改输出内容。</td>
</tr>
<tr>
<td align="left">emitRecords</td>
<td align="left">写入记录</td>
</tr>
<tr>
<td align="left">done</td>
<td align="left">成功完成一次完整的编译和输出流程</td>
</tr>
<tr>
<td align="left">failed</td>
<td align="left">如果在编译和输出的流程中遇到异常，导致Webpack 退出， 就会直接跳转到本步骤，插件可以在本事件中获取具体的错误原因</td>
</tr>
</tbody></table>
<p>更多的事件钩子请求查看这里：<a target="_blank" rel="noopener" href="https://github.com/webpack/webpack/blob/master/lib/Compiler.js##L45">Compiler对象事件</a>、<a target="_blank" rel="noopener" href="https://github.com/webpack/webpack/blob/master/lib/Compilation.js##L250">Compilation对象事件</a>。</p>
<h2 id="5-继续编写插件"><a href="#5-继续编写插件" class="headerlink" title="5. 继续编写插件"></a>5. 继续编写插件</h2><p>知道了广播了哪些事件之后，我们就可以在 <code>apply</code> 中监听事件并编写相应的逻辑啦。</p>
<h3 id="5-1-监听事件和相应逻辑"><a href="#5-1-监听事件和相应逻辑" class="headerlink" title="5.1 监听事件和相应逻辑"></a>5.1 监听事件和相应逻辑</h3><p>如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">XXXPlugin</span> </span>&#123;</span><br><span class="line">  <span class="comment">// 在构造函数中获取用户给该插件传入的配置</span></span><br><span class="line">  <span class="function"><span class="title">constructor</span>(<span class="params">options</span>)</span> &#123;</span><br><span class="line">    <span class="built_in">this</span>.options = options;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// Webpack 会调用 XXXPlugin 实例的 apply 方法给插件实例传入 compiler 对象</span></span><br><span class="line">  <span class="function"><span class="title">apply</span>(<span class="params">compiler</span>)</span> &#123;</span><br><span class="line">    <span class="comment">// 监听某个事件</span></span><br><span class="line">    compiler.hooks.</span><br><span class="line">    <span class="string">&#x27;compiler事件名称&#x27;</span>.tap(<span class="string">&#x27;XXXPlugin&#x27;</span>, <span class="function">(<span class="params">compilation</span>) =&gt;</span> &#123;</span><br><span class="line">      <span class="comment">// 编写相应逻辑</span></span><br><span class="line">        </span><br><span class="line">    &#125;);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 导出 Plugin</span></span><br><span class="line"><span class="built_in">module</span>.exports = XXXPlugin;</span><br></pre></td></tr></table></figure>

<p>当我们监听 <code>Compiler</code> 对象事件中的 <code>compilation</code> 事件时，此时可以在回调函数中再次监听 <code>compilation</code> 对象里的事件，如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">XXXPlugin</span> </span>&#123;</span><br><span class="line">  <span class="comment">// 在构造函数中获取用户给该插件传入的配置</span></span><br><span class="line">  <span class="function"><span class="title">constructor</span>(<span class="params">options</span>)</span> &#123;</span><br><span class="line">    <span class="built_in">this</span>.options = options;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// Webpack 会调用 XXXPlugin 实例的 apply 方法给插件实例传入 compiler 对象</span></span><br><span class="line">  <span class="function"><span class="title">apply</span>(<span class="params">compiler</span>)</span> &#123;</span><br><span class="line">    <span class="comment">// 监听某个事件</span></span><br><span class="line">    compiler.hooks.compilation.tap(<span class="string">&quot;XXXPlugin&quot;</span>, <span class="function">(<span class="params">compilation</span>) =&gt;</span> &#123;</span><br><span class="line">      compilation.hooks.</span><br><span class="line">      <span class="string">&#x27;compiler事件名称&#x27;</span>.tap(<span class="string">&#x27;optimize&#x27;</span>, <span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">// 编写相应逻辑</span></span><br><span class="line">          </span><br><span class="line">      &#125;);</span><br><span class="line">    &#125;);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 导出 Plugin</span></span><br><span class="line"><span class="built_in">module</span>.exports = XXXPlugin;</span><br></pre></td></tr></table></figure>

<h3 id="5-2-异步插件"><a href="#5-2-异步插件" class="headerlink" title="5.2 异步插件"></a>5.2 异步插件</h3><p>有一些事件使用了异步钩子 <code>AsyncHook</code> ，此时在监听这些事件的时候我们就需要使用 <code>tapAsync</code> 或 <code>tapPromise</code> ，并且还需要额外传入一个 <code>callback</code> 回调函数，在插件运行结束时，必须调用这个回调函数，如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">XXXPlugin</span> </span>&#123;</span><br><span class="line">  <span class="comment">// 在构造函数中获取用户给该插件传入的配置</span></span><br><span class="line">  <span class="function"><span class="title">constructor</span>(<span class="params">options</span>)</span> &#123;</span><br><span class="line">    <span class="built_in">this</span>.options = options;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// Webpack 会调用 XXXPlugin 实例的 apply 方法给插件实例传入 compiler 对象</span></span><br><span class="line">  <span class="function"><span class="title">apply</span>(<span class="params">compiler</span>)</span> &#123;</span><br><span class="line">    <span class="comment">// 监听某个事件</span></span><br><span class="line">    compiler.hooks.emit.tapAsync(<span class="string">&quot;XXXPlugin&quot;</span>, <span class="function">(<span class="params">compilation, callback</span>) =&gt;</span> &#123;</span><br><span class="line">      <span class="built_in">setTimeout</span>(<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&quot;异步任务完成&quot;</span>);</span><br><span class="line">        callback();</span><br><span class="line">      &#125;, <span class="number">500</span>);</span><br><span class="line">    &#125;);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 导出 Plugin</span></span><br><span class="line"><span class="built_in">module</span>.exports = XXXPlugin;</span><br></pre></td></tr></table></figure>

<p>OK，以上就是编写一个 <code>webpack</code> 插件所有需要用到的东西，接下里我们就来编写一个简单的插件做个示例。</p>
<h2 id="6-插件示例"><a href="#6-插件示例" class="headerlink" title="6. 插件示例"></a>6. 插件示例</h2><p>在这里我们编写一个简单的插件，该插件的功能是：将 <code>webpack</code> 输出的所有文件打包压缩成一个 <code>zip</code> 压缩包，该插件接收一个配置参数 <code>filename</code> ，表示最终生成的压缩包文件名称。其代码如下：</p>
<p>定义 <code>ZipPlugin</code> 插件：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> &#123;</span><br><span class="line">  RawSource</span><br><span class="line">&#125; = <span class="built_in">require</span>(<span class="string">&quot;webpack-sources&quot;</span>);</span><br><span class="line"><span class="keyword">const</span> JSZip = <span class="built_in">require</span>(<span class="string">&quot;jszip&quot;</span>);</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ZipPlugin</span> </span>&#123;</span><br><span class="line">  <span class="function"><span class="title">constructor</span>(<span class="params">options</span>)</span> &#123;</span><br><span class="line">    <span class="built_in">this</span>.options = options;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="function"><span class="title">apply</span>(<span class="params">compiler</span>)</span> &#123;</span><br><span class="line">    compiler.hooks.emit.tapAsync(<span class="string">&quot;ZipPlugin&quot;</span>, <span class="function">(<span class="params">compilation, callback</span>) =&gt;</span> &#123;</span><br><span class="line">      <span class="keyword">var</span> zip = <span class="keyword">new</span> JSZip();</span><br><span class="line">      <span class="keyword">for</span> (<span class="keyword">let</span> filename <span class="keyword">in</span> compilation.assets) &#123;</span><br><span class="line">        <span class="keyword">const</span> source = compilation.assets[filename].source();</span><br><span class="line">        zip.file(filename, source);</span><br><span class="line">      &#125;</span><br><span class="line">      zip.generateAsync(&#123;</span><br><span class="line">        type: <span class="string">&quot;nodebuffer&quot;</span></span><br><span class="line">      &#125;).then(<span class="function"><span class="params">content</span> =&gt;</span> &#123;</span><br><span class="line">        compilation.assets[<span class="built_in">this</span>.options.filename || <span class="string">&#x27;fileList.zip&#x27;</span>] = <span class="keyword">new</span> RawSource(content);</span><br><span class="line">        callback();</span><br><span class="line">      &#125;);</span><br><span class="line">    &#125;);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">module</span>.exports = ZipPlugin;</span><br></pre></td></tr></table></figure>

<p>代码说明：</p>
<ol>
<li>首先获取到用户传入的配置对象，将其存入<code>this.options</code>内。</li>
<li>我们要想在<code>webpack</code>输出完成后将输出的所有文件打包成<code>zip</code>压缩包，那么就必须监听<code>webpack</code>输出完成后的那个事件，即<code>emit</code>事件。并且该事件为异步事件，所以使用<code>tabAsync</code>监听。</li>
<li>通过<code>webpack</code>的输出资源对象<code>compilation.assets</code>获取到输出的所有文件，遍历这些文件，使用<code>JSZip</code>包将这些文件都放入一个<code>zip</code>压缩包内。</li>
<li>然后将这个压缩包挂载到<code>webpack</code>的输出资源对象<code>compilation.assets</code>上，使其跟随输出资源一同被输出，该压缩包的文件名使用用户传入的<code>filename</code>，如果用户未传入则使用默认的名字<code>fileList.zip</code>。</li>
<li>最后由于是异步事件，在运行结束时，必须调用<code>callback()</code></li>
</ol>
<p>使用 <code>ZipPlugin</code> 插件：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> ZipPlugin = <span class="built_in">require</span>(<span class="string">&#x27;./src/plugins/ZipPlugin&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">  entry: <span class="string">&#x27;./src/index.js&#x27;</span>,</span><br><span class="line">  output: &#123;</span><br><span class="line">    path: path.resolve(<span class="string">&#x27;dist&#x27;</span>),</span><br><span class="line">    filename: <span class="string">&#x27;bundle.js&#x27;</span></span><br><span class="line">  &#125;,</span><br><span class="line">  plugins: [</span><br><span class="line">    <span class="comment">// 使用ZipPlugin插件</span></span><br><span class="line">    <span class="keyword">new</span> ZipPlugin(&#123;</span><br><span class="line">      filename: <span class="string">&#x27;XXX.zip&#x27;</span></span><br><span class="line">    &#125;)</span><br><span class="line">  ]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="7-总结"><a href="#7-总结" class="headerlink" title="7. 总结"></a>7. 总结</h2><p>那么我们可以简单总结一下，一个插件的构成部分：</p>
<ul>
<li>一个插件就是一个类。</li>
<li>在插件类上定义一个 <code>apply</code> 方法。</li>
<li>在<code>apply</code>方法中监听一个<code>webpack</code> 自身的事件钩子。</li>
<li>处理 <code>webpack</code> 内部实例的特定数据。</li>
<li>功能完成后调用 <code>webpack</code> 提供的回调。</li>
</ul>
<p>相信读完这篇文章，你应该就能写出一个自己的插件了。</p>

    </div>

    
    
    
      
<div>
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
</div>
        

  <div class="followme">
    <p>欢迎关注我的其它发布渠道</p>

    <div class="social-list">

        <div class="social-item">
          <a target="_blank" class="social-link" href="/atom.xml">
            <span class="icon">
              <i class="fa fa-rss"></i>
            </span>

            <span class="label">RSS</span>
          </a>
        </div>
    </div>
  </div>


      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/%E5%AE%9E%E6%88%98/" rel="tag"><i class="fa fa-tag"></i> 实战</a>
              <a href="/tags/webpack/" rel="tag"><i class="fa fa-tag"></i> webpack</a>
              <a href="/tags/%E6%8F%92%E4%BB%B6/" rel="tag"><i class="fa fa-tag"></i> 插件</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2021/06/02/%E7%89%9B%E5%AE%A2%E7%BD%91%E5%89%8D%E7%AB%AF%E9%A2%98%E5%BA%9375%E9%81%93%E8%AF%A6%E8%A7%A3/" rel="prev" title="牛客网前端题库详解">
      <i class="fa fa-chevron-left"></i> 牛客网前端题库详解
    </a></div>
      <div class="post-nav-item">
    <a href="/2021/06/06/Rollup%20%E2%80%94%E2%80%94%20%E9%80%82%E5%90%88%E6%A1%86%E6%9E%B6%E5%92%8C%E7%B1%BB%E5%BA%93%E4%BD%BF%E7%94%A8%E7%9A%84%E6%A8%A1%E5%9D%97%E6%89%93%E5%8C%85%E5%99%A8/" rel="next" title="Rollup——适合框架和类库使用的模块打包器">
      Rollup——适合框架和类库使用的模块打包器 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E5%89%8D%E8%A8%80"><span class="nav-text">1. 前言</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-webpack%E8%BF%90%E8%A1%8C%E6%9C%BA%E5%88%B6"><span class="nav-text">2. webpack运行机制</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-%E7%BC%96%E5%86%99%E6%8F%92%E4%BB%B6"><span class="nav-text">3. 编写插件</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-webpack%E5%B7%A5%E4%BD%9C%E6%B5%81%E7%A8%8B"><span class="nav-text">4. webpack工作流程</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#4-1-%E5%88%9D%E5%A7%8B%E5%8C%96%E9%98%B6%E6%AE%B5"><span class="nav-text">4.1 初始化阶段</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-2-%E7%BC%96%E8%AF%91%E9%98%B6%E6%AE%B5"><span class="nav-text">4.2 编译阶段</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-3-%E8%BE%93%E5%87%BA%E9%98%B6%E6%AE%B5"><span class="nav-text">4.3 输出阶段</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-%E7%BB%A7%E7%BB%AD%E7%BC%96%E5%86%99%E6%8F%92%E4%BB%B6"><span class="nav-text">5. 继续编写插件</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#5-1-%E7%9B%91%E5%90%AC%E4%BA%8B%E4%BB%B6%E5%92%8C%E7%9B%B8%E5%BA%94%E9%80%BB%E8%BE%91"><span class="nav-text">5.1 监听事件和相应逻辑</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-2-%E5%BC%82%E6%AD%A5%E6%8F%92%E4%BB%B6"><span class="nav-text">5.2 异步插件</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#6-%E6%8F%92%E4%BB%B6%E7%A4%BA%E4%BE%8B"><span class="nav-text">6. 插件示例</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#7-%E6%80%BB%E7%BB%93"><span class="nav-text">7. 总结</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="hxy"
      src="/images/Robben.gif">
  <p class="site-author-name" itemprop="name">hxy</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">80</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">8</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">120</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/huxingyi1997" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;huxingyi1997" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:huxingyi1997@zju.edu.cn" title="E-Mail → mailto:huxingyi1997@zju.edu.cn" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-frog"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">hxy</span>
</div>

<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共1039.2k字</span>
</div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/lozad@1/dist/lozad.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  




  
<script src="/js/local-search.js"></script>













  

  


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : true,
      appId      : 'pQsO3ySbU4VtWN2j1FLA74Ha-gzGzoHsz',
      appKey     : 'QYacMDY2VY7Wazprg1X6FiUv',
      placeholder: "Just go go",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : false,
      lang       : 'zh-cn' || 'zh-cn',
      path       : location.pathname,
      recordIP   : false,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>

  
  <!-- 动态背景特效 -->
  <!-- 樱花特效 -->
    <script async src="/js/src/sakura.js"></script>
    <script async src="/js/src/fairyDustCursor.js"></script>
</body>
</html>
